package org.middleware.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.util.Base64;
import java.util.Date;

@Component
public class JwtTokenUtil {

    @Value("${jwt.secret:defaultSecretKey}")
    private String secret;

    private static final long expire = 86400000; // 24小时

    private SecretKey getSigningKey() {
        try {
            byte[] keyBytes = Base64.getDecoder().decode(secret);
            return Keys.hmacShaKeyFor(keyBytes);
        } catch (Exception e) {
            throw new RuntimeException("JWT密钥配置错误，请检查secret是否为有效的Base64编码", e);
        }
    }

    /**
     * 创建 Token
     * @param username 用户名
     * @return Token字符串
     */
    public String generateToken(String username) {
        return Jwts.builder()
                .setSubject(username)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + expire))
                .signWith(getSigningKey())
                .compact();
    }

    /**
     * 通过 Token 获取用户名
     * @param token
     * @return
     */
    public String getUsernameFromToken(String token) {
        Claims claims = Jwts.parserBuilder()
                .setSigningKey(getSigningKey())
                .build()
                .parseClaimsJws(token)
                .getBody();
        return claims.getSubject();
    }

    /**
     * 验证 Token是否生效
     * @param token
     * @return
     */
    public boolean validateToken(String token) {
        try {
            Jwts.parserBuilder()
                    .setSigningKey(getSigningKey())
                    .build()
                    .parseClaimsJws(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 验证密钥格式（可选，用于初始化检查）
     */
    public void validateSecretKey() {
        try {
            byte[] decoded = Base64.getDecoder().decode(secret);
            if (decoded.length < 64) { // HS512需要至少512位（64字节）
                throw new IllegalArgumentException("JWT密钥长度不足，至少需要512位（64字节）");
            }
        } catch (IllegalArgumentException e) {
            throw new RuntimeException("JWT密钥必须是有效的Base64编码字符串", e);
        }
    }
}